package com.idudiao.sc.common.core.validator;

import cn.hutool.core.util.StrUtil;
import com.idudiao.sc.common.core.validator.constraints.Special;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 特殊字符校验
 *
 * @author xushuai
 * @since 2019/2/28 11:29
 */
public class SpecialValidator implements ConstraintValidator<Special, String> {

    /**
     * 不得出现“？”、“！”、“$”、“%”、“^”、“*” 字符。（“？”和“！”包含全角和半角两种格式，其他字符为半角字符。）
     */
    private static final String VALIDATOR_CHAR = "[？！?!$%^*]";

    @Override
    public void initialize(Special constraintAnnotation) {

    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (StrUtil.isBlank(value)) {
            return true;
        }
        Pattern pattern = Pattern.compile(VALIDATOR_CHAR);
        Matcher m = pattern.matcher(value);
        return !m.find();
    }

}
